<template>
  <div class="shipping">
    <el-form :model="search" inline>
      <el-form-item>
        <el-input v-model="search.sellerName" placeholder="商家名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="search.mobile" placeholder="商家手机号码" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="searchHandle">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="add">添加运费模板</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column label="模板名称" align="center" prop="transName" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column label="商家名称" align="center" prop="sellerName" width="200" show-overflow-tooltip></el-table-column>
      <el-table-column label="计费方式" align="center" width="160">
        <template slot-scope="scope">
          <span>{{scope.row.chargeType==0?'按件数计费':'按重量计费'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="物流公司" align="center" prop="courierName"></el-table-column>
      <el-table-column label="是否包邮" align="center" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.isFreeFee==0?'不包邮':'包邮'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="包邮金额" align="center" prop="amount"></el-table-column>
      <el-table-column label="首重(首件)价格" align="center" prop="firstFee" width="120"></el-table-column>
      <el-table-column label="首重(首件)数量" align="center" prop="firstPiece" width="120"></el-table-column>
      <el-table-column label="续重(续件)价格" align="center" prop="continuousFee" width="120"></el-table-column>
      <el-table-column label="续重(续件)数量" align="center" prop="continuousPiece" width="120"></el-table-column>
      <el-table-column label="是否启用" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isActive" @change="changeHandle(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="update(scope.row)">编辑</el-button>
          <!-- <el-button type="danger" size="mini" @click="remove(scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <div class="pages">
      <el-pagination :page-size="size" :current-page="page" layout="prev, pager, next,total,jumper" :total="total"
        background @current-change="handleCurrentChange">
      </el-pagination>
    </div>

    <el-dialog :title="title" :visible.sync="visible" width="70%">
      <el-form label-width="120px" :model="formData" :rules="rules" ref="ruleForm">
        <el-form-item label="商家名称">
          <el-autocomplete v-model="formData.sellerName" :fetch-suggestions="querySearchAsync" placeholder="请输入商家名称"
            clearable style="width:280px;" @select="handleSelect" disabled></el-autocomplete>
        </el-form-item>

        <el-form-item label="模板名称">
          <el-input v-model="formData.transName" placeholder="请输入模板名称" style="width: 240px;"></el-input>
        </el-form-item>


        <el-form-item label="计价方式">
          <el-radio-group v-model="formData.chargeType">
            <el-radio :label="0">按件计费</el-radio>
            <el-radio :label="1">按重量计费</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="物流公司">
          <el-select v-model="formData.courierName" placeholder="请选择物流公司">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否包邮" v-show="formData.chargeType==0">
          <el-switch v-model="formData.isFreeFee">
          </el-switch>
        </el-form-item>

        <el-form-item label="包邮条件" v-show="formData.isFreeFee">
          <span>满</span>
          <el-input-number v-model="formData.amount" :min="0" class="numInput"></el-input-number>
          <span style="padding-right: 8px;">包邮</span>
          <el-tooltip content="如设置为0表示包邮无金额限制" placement="top-start">
            <span style="cursor: pointer;">?</span>
          </el-tooltip>
        </el-form-item>

        <el-form-item :label="formData.chargeType==0?'默认计费':'首重'">
          <el-input-number v-if="formData.chargeType==1" v-model="formData.firstPiece" :min="1" style="width: 100px;" controls-position="right"></el-input-number>
          <span v-else-if="formData.chargeType==0">{{formData.firstPiece}}</span>
          <span style="padding:0 10px;">{{formData.chargeType==0?'件':'千克'}}内</span>
          <el-input-number v-model="formData.firstFee" :min="0" style="width: 100px;" controls-position="right"></el-input-number>
          <span style="padding:0 10px;">元, 每增加</span>
          <span>{{formData.continuousPiece}}</span>
          <span style="padding:0 10px;">{{formData.chargeType==0?'件':'千克'}}, 增加运费 </span>
          <el-input-number v-model="formData.continuousFee" :min="0" style="width: 100px;" controls-position="right"></el-input-number>
          <span style="padding:0 10px;">元</span>
        </el-form-item>

        <el-form-item>
          <el-tag>除特定地区外, 其余地区的运费采用默认计费</el-tag>
        </el-form-item>

        <el-form-item style="margin-bottom:5px;" v-show="formData.specialAreasVo.length>0">
          <el-row :gutter="10">
            <el-col :span="5" style="display: flex;justify-content: center;">特定地区</el-col>
            <el-col :span="4" style="display: flex;justify-content: center;">{{formData.chargeType==0?'首件':'首重(千克)'}}</el-col>
            <el-col :span="4" style="display: flex;justify-content: center;">首费(元)</el-col>
            <el-col :span="4" style="display: flex;justify-content: center;">{{formData.chargeType==0?'续件':'续重(千克)'}}</el-col>
            <el-col :span="4" style="display: flex;justify-content: center;">续费(元)</el-col>
            <el-col :span="2" style="display: flex;justify-content: center;"></el-col>
          </el-row>
        </el-form-item>

        <el-form-item v-for="(item,index) in formData.specialAreasVo" :key="index">
          <el-row :gutter="10">
            <el-col :span="5" style="display: flex;justify-content: center;">
              <el-select multiple v-model="item.cityIdList" placeholder="请选择地区" style="width: 100%;">
                <el-option v-for="item in areaOptions" :key="item.id" :label="item.regionName" :value="item.regionCode">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4" style="display: flex;justify-content: center;">
              <el-input-number v-if="formData.chargeType==1" v-model="item.firstPiece" :min="1" style="width: 100px;" controls-position="right"></el-input-number>
              <span v-else-if="formData.chargeType==0">{{item.firstPiece}}</span>
            </el-col>
            <el-col :span="4" style="display: flex;justify-content: center;">
              <el-input-number v-model="item.firstFee" :min="0" style="width: 100%;" controls-position="right"></el-input-number>
            </el-col>
            <el-col :span="4" style="display: flex;justify-content: center;">
              <span>{{item.continuousPiece}}</span>
            </el-col>
            <el-col :span="4" style="display: flex;justify-content: center;">
              <el-input-number v-model="item.continuousFee" :min="0" style="width: 100%;" controls-position="right"></el-input-number>
            </el-col>
            <el-col :span="2" style="display: flex;justify-content: center;">
              <el-button type="default" @click="removeArea(index)">删除</el-button>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="mini" @click="addArea">添加特定地区</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit('ruleForm')" icon="el-icon-check">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        size: 10,
        page: 1,
        total: 0,
        search: {
          sellerName: '',
          mobile: ''
        },
        tableData: [],
        title: '',
        visible: false,
        options: [{
          value: '0',
          label: '顺丰速运'
        }, {
          value: '1',
          label: '中国邮政'
        }, {
          value: '2',
          label: '圆通速递'
        }, {
          value: '3',
          label: '中通快递'
        }, {
          value: '4',
          label: '申通快递'
        }, {
          value: '5',
          label: '宅急送'
        }, {
          value: '6',
          label: '联邦物流'
        }, {
          value: '7',
          label: '韵达快递'
        }, {
          value: '8',
          label: '京东快递'
        }, {
          value: '9',
          label: '百世快递'
        }, {
          value: '10',
          label: '其他快递'
        }],
        areaOptions: [],
        formData: {
          sellerName: '',
          sellerId: '',
          transName: '',
          mobile: '',
          chargeType: 0,
          courierName: '',
          isFreeFee: false,
          amount: 0,
          firstPiece: 1, //首件数量
          firstFee: '', //首件费用
          continuousPiece: 1, //续件数量
          continuousFee: '', //续件费用
          specialAreasVo: []
        },
        restaurants: [],
        timeout: null,
        rules: {

        },
      }
    },
    mounted() {
      this.getData();
      this.getArea();
      this.getMerchantList();
    },
    methods: {
      searchHandle() {
        this.page = 1;
        this.getData();
      },
      handleCurrentChange(val) {
        this.page = val;
        this.getData();
      },
      getData() {
        this.$http.get(this.$api.shippingList, {
          page: this.page,
          size: this.size,
          sellerName: this.search.sellerName,
          mobile: this.search.mobile,
		  merchantId:localStorage.getItem('merchantId')
        }).then(res => {
          this.tableData = res.data;
          this.total = res.extraInfo;
        })
      },
      getMerchantList() {
        const loading = this.$loading({
                  lock: true,
                  text: 'Loading',
                  spinner: 'el-icon-loading',
                  background: 'rgba(0, 0, 0, 0.7)'
                });
        this.$http.get(this.$api.merchantSimple, {
          query: ''
        }).then(res => {
          loading.close();
          this.restaurants = res.data;
        })
      },
      querySearchAsync(queryString, cb) {
        var restaurants = this.restaurants;
        var merchantData = [];
        restaurants.forEach(item => {
          merchantData.push({
            mid: item.mid,
            mobile: item.usrPhone,
            value: item.namePhone
          });
        })
        var results = queryString ? merchantData.filter(this.createStateFilter(queryString)) : merchantData;
        cb(results);
      },
      createStateFilter(queryString) {
        return (state) => {
          return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      changeHandle(row) {
        this.$http.put(this.$api.shippingIsActive, {
          isActive: row.isActive,
          transportId: row.transportId
        }).then(res => {
          if (res.code == 0) {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
          } else {
            this.$message({
              type: 'success',
              message: '修改失败!'
            });
          }
        })
      },
      handleSelect(val) {
        this.formData.sellerId = val.mid;
        this.formData.mobile = val.mobile;
      },
      getArea() {
        this.$http.get(this.$api.regionList, {
          parentCode: 0
        }).then(res => {
          this.areaOptions = res.data;
        })
      },
      //添加特定区域
      addArea() {
        this.formData.specialAreasVo.push({
          cityIdList: [], //特殊城市id
          firstPiece: 1, //首件数量
          firstFee: '', //首件费用
          continuousPiece: 1, //续件数量
          continuousFee: '', //续件费用
        })
      },
      //移除特定区域
      removeArea(index) {
        this.formData.specialAreasVo.splice(index, 1);
      },
      add() {
        this.formData = {
          sellerName: localStorage.getItem('merName'),
          sellerId: localStorage.getItem('merchantId'),
          transName: '',
          mobile: localStorage.getItem('mobile'),
          chargeType: 0,
          courierName: '',
          isFreeFee: false,
          amount: 0,
          firstPiece: 1, //首件数量
          firstFee: '', //首件费用
          continuousPiece: 1, //续件数量
          continuousFee: '', //续件费用
          specialAreasVo: []
        }
        this.title = '新增运费模板';
        this.visible = true;
      },
      update(row) {
        this.$http.get(this.$api.shippingEdit, {
          transportId: row.transportId
        }).then(res => {
          if (res.code == 0) {
            this.title = '修改运费模板';
            this.visible = true;
            this.formData = res.data;
          } else {
            this.$message.error('服务器报错,请联系管理员处理!');
          }
        })
      },
      remove(row) {
        this.$confirm('此操作将永久删除该运费模板, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.delete(this.$api.shippingDelete + '/' + row.transportId).then(res => {
            if (res.code == 0) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getData();
            } else {
              this.$message.error('删除失败!');
            }
          })
        }).catch(() => {});
      },
      submit(ruleForm) {
        this.$refs[ruleForm].validate((valid) => {
          if (valid) {
            if (this.formData.transportId) {
              this.$http.put(this.$api.shippingUpdate, this.formData).then(res => {
                if (res.code == 0) {
                  this.$message({
                    type: 'success',
                    message: '修改成功'
                  });
                  this.visible = false;
                  this.getData();
                } else {
                  this.$message.error('修改失败！');
                }
              })
            } else {
              this.$http.post(this.$api.shippingAdd, this.formData).then(res => {
                if (res.code == 0) {
                  this.$message({
                    type: 'success',
                    message: '添加成功'
                  });
                  this.visible = false;
                  this.getData();
                } else {
                  this.$message.error('添加失败！');
                }
              })
            }

          }
        })
      }
    }
  }
</script>

<style scoped>
  .shipping {
    padding: 15px;
  }

  .pages {
    display: flex;
    justify-content: center;
    margin: 30px 0;
  }

  .numInput {
    width: 160px;
    margin: 0 10px;
  }
</style>
